using MediatR;
using Microsoft.EntityFrameworkCore;
using Medical.Domain;
using Medical.ErrorCode;
using Medical.Infrastructrue.Interfaces;
using Medical.ReadApi.Appcontext.Command;
using Medical.ReadApi.Dto;

namespace Medical.ReadApi.Appcontext.CommandHandler
{
	/// <summary>
	/// 获取挂号单模板列表查询处理器
	/// </summary>
	public class GetRegistrationSlipTemplatesListQueryHandler : IRequestHandler<GetRegistrationSlipTemplatesListQuery, ApiPaging<RegistrationSlipTemplateDto>>
	{
		private readonly IBaseRepository<RegistrationSlipTemplate> _repository;

		public GetRegistrationSlipTemplatesListQueryHandler(IBaseRepository<RegistrationSlipTemplate> repository)
		{
			_repository = repository;
		}

		public async Task<ApiPaging<RegistrationSlipTemplateDto>> Handle(GetRegistrationSlipTemplatesListQuery request, CancellationToken cancellationToken)
		{
			var query = _repository.GetAll().Where(x => !x.IsDeleted);

			// 过滤条件：是否启用
			if (request.IsActive.HasValue)
			{
				query = query.Where(x => x.IsActive == request.IsActive.Value);
			}

			// 搜索条件：模板名称关键字
			if (!string.IsNullOrEmpty(request.TemplateNameKeyword))
			{
				query = query.Where(x => x.TemplateName.Contains(request.TemplateNameKeyword));
			}

			// 获取总数
			var totalCount = await query.CountAsync(cancellationToken);

			// 分页
			var items = await query
				.OrderByDescending(x => x.CreatedAt)
				.Skip((request.Page - 1) * request.Size)
				.Take(request.Size)
				.Select(x => new RegistrationSlipTemplateDto
				{
					TemplateId = x.TemplateId,
					TemplateName = x.TemplateName,
					Description = x.Description,
					IsActive = x.IsActive,
					IsDefault = x.IsDefault,
					PriorityRules = x.PriorityRules,
					ConfiguredFields = x.ConfiguredFields,
					CreatedAt = x.CreatedAt,
					UpdatedAt = x.UpdatedAt
				})
				.ToListAsync(cancellationToken);

			// 计算总页数
			var totalPage = (int)Math.Ceiling(totalCount / (double)request.Size);

			return new ApiPaging<RegistrationSlipTemplateDto>
			{
				totalCount = totalCount,
				totalPage = totalPage,
				data = items
			};
		}
	}
}
